const userModel = require("../Model/users");
const bcrypt = require("bcrypt");
// console.log(bcrypt)
const regist = async (req, res) => {
  //req.body 能够拿到客户端通过post请求传递的数据
  console.log(req.body);
  //1.需要判断用户名和密码是否都传递了
  let { username, password } = req.body;
  if (username && password) {
    //2.通过用户名查找,数据库中是否存在这个用户
    let result = await userModel.find({ username });
    console.log(result);
    let { state, res: ret, errMsg } = result;
    if (state) {
      //查询成功
      if (ret.length) {
        //有长度,表示用户名重复
        res.send({ state: false, status: 30005, msg: "用户已存在" });
      } else {
        //不重复,可以添加到数据库
        // req.body.username = [123123];
        //对密码进行加密
        let saltRounds = 10; //hash杂凑次数 2^10
        let hashPsw = await bcrypt.hash(password, saltRounds);
        // console.log(hashPsw)
        // console.log(req.body);
        req.body.password = hashPsw;
        let regResult = await userModel.add(req.body);
        let { state, res: ret, errMsg } = regResult;
        if (state) {
          //添加成功
          res.send({ state: true, status: 200, msg: "注册成功" });
        } else {
          res.send({ state: false, status: 40001, errMsg });
        }
      }
    } else {
      //查询出错了
      res.send({ state: false, status: 40002, errMsg });
    }
  } else {
    res.send({ state: false, status: 3004, msg: "username和password必传" });
  }
};

const login = async (req, res) => {
  console.log(req.body);
  let { username, password } = req.body;
  //1.先查找没有这个用户 通过用户名查找
  let findRes = await userModel.find({ username });
  let { errMsg } = findRes; //从结果中解构错误信息
  console.log(findRes);
  if (findRes.state) {
    //数据库查询成功了
    let { res: ret } = findRes; //数组
    let obj = ret[0];
    let hashPsw = obj.password;

    let compareRes = await bcrypt.compare(password, hashPsw);
    console.log(compareRes);
    if (compareRes) {
      //密码校验通过
      //脱敏 把敏感信息去掉
      res.send({ state: true, status: 200, info: obj, msg: "登入成功" });
    } else {
      res.send({ state: false, status: 40003, msg: "用户名或者密码错误" });
    }
  } else {
    //查询数据库出错了
    res.send({ state: false, status: 40005, errMsg });
  }
  //2.查找到了 将这个用户的密码取出来(加密之后的)

  //3.用客户端传递的密码和加密的密码进行校验,校验通过 告诉客户端登入成功
};

module.exports = {
  regist,
  login,
};
